package sn.radius.client

import org.aaa4j.radius.core.attribute.Attribute
import org.aaa4j.radius.core.packet.Packet
import scala.jdk.CollectionConverters.*

object PacketUtils {
  extension (packet: Packet)
    /** Replacement of `toString` */
    def text: String =
      s"""Packet(
         |    code = ${packet.getCode}
         |    ${packetAttributesString(packet.getAttributes, offset = " " * 6)}
         |    ${packet.getReceivedFields.text(offset = " " * 6)}
         |)""".stripMargin

  extension (fields: Packet.ReceivedFields)
    def text(offset: String): String =
      s"ReceivedFields: Id=${fields.getIdentifier}, Authenticator=${fields.getAuthenticator.map(b => (b & 0xff).toHexString).mkString("-")}"

  private def packetAttributesString(listAttrs: java.util.List[Attribute[_]], offset: String): String = {
    if (listAttrs == null) "NULL"
    else {
      listAttrs.asScala.map((a: Attribute[_]) => s"$offset${a.getType} = ${a.getData}").mkString("Attributes:\n", "\n   ", "")
    }
  }}

